package org.xiaojl.xcloud.tools.gateway.kit;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

/**  
 * <p>Title: InetKit</p>  
 *
 * <p>Description: 网络工具类</p>  
 *
 * @author jilong.xiao  
 * @date 2018年4月23日  
 */
public class IpKit {
	/**
     * 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址; 
     * @param request
     * @return
     */
    public static String getRequestIp(HttpServletRequest request){
    	// 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址  
        String ip = request.getHeader("X-Forwarded-For"); //X-Forwarded-For：Squid 服务代理
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");//Proxy-Client-IP：apache 服务代理
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");//WL-Proxy-Client-IP：weblogic 服务代理
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");//HTTP_CLIENT_IP：有些代理服务器
        }
        
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");//X-Real-IP：nginx服务代理
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        //有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
        if (ip != null && ip.length() != 0) {
            ip = ip.split(",")[0];
        }
        //还是不能获取到，最后再通过request.getRemoteAddr();获取
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        //使用localhost访问
        if(ip!=null && "0:0:0:0:0:0:0:1".equals(ip)){
        	ip = "127.0.0.1";
        }
        return ip;
    }
    
	/**
	 * 获取本地IP地址
	 */
	public static String getLocalIp() {
		if (isWindowsOS()) {
			return getLocalHostAddress();
		} else {
			return getLinuxLocalIp();
		}
	}

	/**
	 * 判断操作系统是否是Windows
	 * @return
	 */
	public static boolean isWindowsOS() {
		boolean isWindowsOS = false;
		String osName = System.getProperty("os.name");
		if (osName.toLowerCase().indexOf("windows") > -1) {
			isWindowsOS = true;
		}
		return isWindowsOS;
	}

	/**
	 * 获取本地Host地址
	 */
	public static String getLocalHostAddress(){
		try {
			return InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			System.err.println("获取ip地址异常:"+e.getMessage());
		}
		return "127.0.0.1";
	}

	/**
	 * 获取Linux下的IP地址
	 *
	 * @return IP地址
	 * @throws SocketException
	 */
	private static String getLinuxLocalIp(){
		String ip = "";
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				String name = intf.getName();
				if (!name.contains("docker") && !name.contains("lo")) {
					for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
						InetAddress inetAddress = enumIpAddr.nextElement();
						if (!inetAddress.isLoopbackAddress()) {
							String ipaddress = inetAddress.getHostAddress().toString();
							if (!ipaddress.contains("::") && !ipaddress.contains("0:0:")
									&& !ipaddress.contains("fe80")) {
								ip = ipaddress;
							}
						}
					}
				}
			}
		} catch (SocketException ex) {
			System.err.println("获取ip地址异常:"+ex.getMessage());
			ip = "127.0.0.1";
		}
		return ip;
	}
	
	/*//用来获取每个URL请求的完全链接,附带请求参数
    public static String getUrl(HttpServletRequest request , HttpServletResponse response){
        StringBuffer uri = request.getRequestURL();
        String url = uri.toString();
        //获取所有请求,返回Map集合,遍历
        Map<String, String[]> map = request.getParameterMap();
        Set<Entry<String, String[]>> entry = map.entrySet();
        Iterator<Entry<String, String[]>> iterator = entry.iterator();
        //遍历集合
        StringBuffer sb = new StringBuffer();
        while(iterator.hasNext()){
            Entry<String, String[]> item = iterator.next();
            //请求名
            String key = item.getKey();
            //请求值
            for(String value : item.getValue()){
                //拼接每个请求参数   key=value&
                sb.append(key+"="+value+"&");
            }
        }
        String string = sb.toString();
        //拼接URL,   URL?key=value&key=value&   并且去掉最后一个&
        url = url+"?"+string.substring(0, string.lastIndexOf("&"));
        return url;
    }*/

	public static void main(String[] args) throws UnknownHostException {
		 System.out.println(getLocalIp());
	}
}
